<template>
    <div>
        <div class="filter-and-option">
            <!-- 分类筛选 -->
            <el-select v-model="filterData.category" clearable placeholder="筛选分类" style="margin-bottom: 20px; width: 200px;" @change="filterRules">
                <el-option v-for="(category, index) in categories" :key="index" :label="category" :value="category" />
            </el-select>
            <!-- 添加规则按钮 -->
            <el-button type="primary" @click="openModal">添加规则</el-button>
        </div>
        
        <!-- 添加/编辑规则模态框 -->
        <el-dialog :title="isEditing ? '编辑规则' : '添加规则'" v-model="isModalVisible" width="500px" :rules="rulesValidation" :before-close="closeModal">
            <el-form :model="form" :rules="rulesValidation" ref="formRef" label-width="80px" class="modal-form">
                <el-form-item label="分类" prop="category">
                    <el-select v-model="form.category" placeholder="请选择分类" required>
                        <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目名称" prop="item">
                    <el-input v-model="form.item" required />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="form.description" required />
                </el-form-item>
                <el-divider border-style="dashed" />
                <el-form-item label="山长加分">
                    <el-radio-group v-model="form.isLeader">
                        <el-radio :value="1" size="large">范围得分</el-radio>
                        <el-radio :value="2" size="large">固定得分</el-radio>
                        <el-radio :value="0" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div v-if="form.isLeader !== 0">
                    <el-form-item label="固定加分" v-if="form.isLeader === 2">
                        <el-input-number v-model="form.rules.leader.fixedScore" :step="0.5" step-strictly />
                    </el-form-item>
                    <el-form-item label="得分范围" v-else>
                        <el-input-number v-model="form.rules.leader.minScore" :step="0.5" step-strictly /> -
                        <el-input-number v-model="form.rules.leader.maxScore" :step="0.5" step-strictly />
                    </el-form-item>
                    <el-form-item label="封顶得分" >
                        <el-switch v-model="form.rules.leader.isTop" />
                        <el-input-number v-model="form.rules.leader.topScore" :step="0.5" step-strictly :disabled="!form.rules.leader.isTop" />
                    </el-form-item>
                </div>
                <el-divider border-style="dashed" />
                <el-form-item label="师门加分">
                    <el-radio-group v-model="form.isMaster">
                        <el-radio :value="1" size="large">范围得分</el-radio>
                        <el-radio :value="2" size="large">固定得分</el-radio>
                        <el-radio :value="0" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div v-if="form.isMaster !== 0">
                    <el-form-item label="固定加分" v-if="form.isMaster === 2">
                        <el-input-number v-model="form.rules.master.fixedScore" :step="0.5" step-strictly />
                    </el-form-item>
                    <el-form-item label="得分范围" v-else>
                        <el-input-number v-model="form.rules.master.minScore" :step="0.5" step-strictly /> -
                        <el-input-number v-model="form.rules.master.maxScore" :step="0.5" step-strictly />
                    </el-form-item>
                    <el-form-item label="封顶得分" >
                        <el-switch v-model="form.rules.master.isTop" />
                        <el-input-number v-model="form.rules.master.topScore" :step="0.5" step-strictly :disabled="!form.rules.master.isTop" />
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeModal">取消</el-button>
                <el-button type="primary" @click="handleAddOrUpdate">保存</el-button>
            </div>
        </el-dialog>

        <!-- 规则列表 -->
        <el-table :data="rules" style="width: 100%; margin-top: 20px">
            <el-table-column prop="category" label="分类" width="150"/>
            <el-table-column prop="item" label="项目名称" width="150"/>
            <el-table-column prop="description" label="描述" show-overflow-tooltip/>
            <el-table-column prop="leader-rules" label="山长加分规则" width="200">
                <template #default="scope">
                    <div v-if="[0,2].includes(scope.row.rules.isMasterScore)">
                        <div v-if="scope.row.rules.leader.minScore === scope.row.rules.leader.maxScore">
                            固定加分：{{ scope.row.rules.leader.minScore }}
                        </div>
                        <div v-else>
                            得分范围：{{ scope.row.rules.leader.minScore }} - {{ scope.row.rules.leader.maxScore }}
                        </div>
                        <div>
                            封顶得分：{{ scope.row.rules.leader.topScore > 0 ? scope.row.rules.leader.topScore : '不封顶' }}
                        </div>
                    </div>
                    <div v-else>
                        无
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="master-rules" label="师门加分规则" width="200">
                <template #default="scope">
                    <div v-if="[1,2].includes(scope.row.rules.isMasterScore)">
                        <div v-if="scope.row.rules.master.minScore === scope.row.rules.master.maxScore">
                            固定加分：{{ scope.row.rules.master.minScore }}
                        </div>
                        <div v-else>
                            得分范围：{{ scope.row.rules.master.minScore }} - {{ scope.row.rules.master.maxScore }}
                        </div>
                        <div>
                            封顶得分：{{ scope.row.rules.master.topScore > 0 ? scope.row.rules.master.topScore : '不封顶' }}
                        </div>
                    </div>
                    <div v-else>
                        无
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button size="small" @click="editRule(scope.row)">编辑</el-button>
                    <el-popconfirm title="确定删除这条规则吗">
                        <template #reference>
                            <el-button size="small" type="danger">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                          <el-button size="small" @click="cancel">否</el-button>
                          <el-button type="danger" size="small" @click="deleteRule(scope.row.id)">是</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { RuleService } from '@/service/RuleService';
import { ScoringRule } from '@/domain/ScoringRule';
import { ElMessage } from 'element-plus';
import type { FormRules, FormContext, FormInstance } from 'element-plus';


// 表单数据
const form = ref({
    id: new Date().getTime(),
    category: '',
    item: '',
    description: '',
    isLeader: 2,
    isMaster: 0,
    rules: {
        leader: {
            minScore: 0,
            maxScore: 2,
            defaultScore: 0,
            topScore: 50,
            fixedScore: 0,
            isTop: true,
        },
        master: {
            minScore: 0,
            maxScore: 2,
            defaultScore: 0,
            topScore: 50,
            fixedScore: 0,
            isTop: false,
        },
        // 是否为山长加分（0），或者师门加分（1），如果都有，则为（2）
        isMasterScore: 2,
    } as any // Add type assertion to avoid type errors
});

interface RuleForm {
    id: number;
    category: string;
    item: string;
    description: string;
    isLeader: number;
    isMaster: number;
    rules: {
        leader: {
            minScore: number;
            maxScore: number;
            defaultScore: number;
            topScore: number;
            fixedScore: number;
            isTop: boolean;
        };
        master: {
            minScore: number;
            maxScore: number;
            defaultScore: number;
            topScore: number;
            fixedScore: number;
            isTop: boolean;
        };
        isMasterScore: number;
    };
}

// 当前筛选数据
const filterData = ref({
    category: '',
});

// 是否处于编辑模式
const isEditing = ref(false);

// 是否显示模态框
const isModalVisible = ref(false);

// 所有规则
const rules = ref<ScoringRule[]>([]);

// 规则分类
const categories = ScoringRule.categories;

// 表单校验
const rulesValidation = reactive<FormRules<RuleForm>>({
    category: [
        { required: true, message: '请选择分类', trigger: 'change' },
    ],
    item: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
    description: [
        { required: true, message: '请输入描述', trigger: 'blur' },
    ],
});

// 加载规则数据
const loadRules = () => {
    rules.value = JSON.parse(JSON.stringify(RuleService.getAllRules()));
};

// 筛选规则
const filterRules = () => {
    const allRules = RuleService.getAllRules();
    if (filterData.value.category) {
        rules.value = allRules.filter(rule => rule.category === filterData.value.category);
    } else {
        rules.value = allRules;
    }
};

// 打开模态框
const openModal = () => {
    if (!isEditing.value) {
        resetForm();
    }
    isModalVisible.value = true;
};

// 关闭模态框
const closeModal = () => {
    resetForm();
    isModalVisible.value = false;
    isEditing.value = false;
};

const formRef = ref<FormInstance>();

const handleAddOrUpdate = () => {
    formRef.value?.validate((valid) => {
        if (!valid) {
            ElMessage.error('请检查表单填写是否正确');
            return;
        }

        let ruleScores = {
            leader: {
                minScore: 0,
                maxScore: 0,
                defaultScore: 0,
                topScore: 50,
            },
            master: {
                minScore: 0,
                maxScore: 0,
                defaultScore: 0,
                topScore: 50,
            },
            isMasterScore: 2,
        };

        // 山长加分和师门加分不能同时为否
        if (form.value.isLeader == 0 && form.value.isMaster == 0) {
            ElMessage.error('山长加分和师门加分不能同时为否， 否则这不是一个有效的积分项');
            return;
        }

        // 根据加分类型调整规则分数
        if (form.value.isLeader === 0) {
            ruleScores.leader = {
                minScore: 0,
                maxScore: 0,
                defaultScore: 0,
                topScore: 50,
            };
        } else if (form.value.isLeader === 1) {
            // 先判断范围加分是否合理
            if (form.value.rules.leader.minScore > form.value.rules.leader.maxScore) {
                ElMessage.error('山长加分的最小分数不能大于最大分数');
                return;
            }
            ruleScores.leader = {
                minScore: form.value.rules.leader.minScore,
                maxScore: form.value.rules.leader.maxScore,
                defaultScore: form.value.rules.leader.defaultScore,
                topScore: form.value.rules.leader.isTop ? form.value.rules.leader.topScore : -1,
            }; 
        } else {
            ruleScores.leader = {
                minScore: form.value.rules.leader.fixedScore,
                maxScore: form.value.rules.leader.fixedScore,
                defaultScore: form.value.rules.leader.fixedScore,
                topScore: form.value.rules.leader.isTop ? form.value.rules.leader.topScore : -1,
            };
        }
        if (form.value.isMaster === 0) {
            ruleScores.master = {
                minScore: 0,
                maxScore: 0,
                defaultScore: 0,
                topScore: 50,
            };
        } else if (form.value.isMaster === 1) {
            // 先判断范围加分是否合理
            if (form.value.rules.master.minScore > form.value.rules.master.maxScore) {
                ElMessage.error('师门加分的最小分数不能大于最大分数');
                return;
            }
            ruleScores.master = {
                minScore: form.value.rules.master.minScore,
                maxScore: form.value.rules.master.maxScore,
                defaultScore: form.value.rules.master.defaultScore,
                topScore: form.value.rules.master.isTop ? form.value.rules.master.topScore : -1,
            };
        } else {
            ruleScores.master = {
                minScore: form.value.rules.master.fixedScore,
                maxScore: form.value.rules.master.fixedScore,
                defaultScore: form.value.rules.master.fixedScore,
                topScore: form.value.rules.master.isTop ? form.value.rules.master.topScore : -1,
            };
        }
        // 确定isMasterScore值
        if (form.value.isLeader !== 0 && form.value.isMaster !== 0) {
            ruleScores.isMasterScore = 2;
        } else if (form.value.isLeader !== 0) {
            ruleScores.isMasterScore = 0;
        } else {
            ruleScores.isMasterScore = 1;
        }
        // 封装
        const newRule = new ScoringRule(
            form.value.category,
            form.value.item,
            form.value.description,
            ruleScores
        );

        if (isEditing.value) {
            newRule.id = form.value.id;
        }

        RuleService.saveRule(newRule);
        ElMessage.success(isEditing.value ? '规则更新成功' : '规则添加成功');
        loadRules();
        closeModal();
    });
};

// 编辑规则
const editRule = (rule: ScoringRule) => {
    // 重置表单
    resetForm();

    // 基础数据
    form.value.id = rule.id;
    form.value.category = rule.category;
    form.value.item = rule.item;
    form.value.description = rule.description;
    form.value.isLeader = 0;
    form.value.isMaster = 0;

    // 山长加分
    if ([0, 2].includes(rule.rules.isMasterScore)) {
        // 分数范围
        if (rule.rules.leader.minScore === rule.rules.leader.maxScore) {
            // 固定的分数
            form.value.isLeader = 2;
            form.value.rules.leader.fixedScore = rule.rules.leader.minScore;
        } else {
            // 范围分数
            form.value.isLeader = 1;
            form.value.rules.leader.minScore = rule.rules.leader.minScore;
            form.value.rules.leader.maxScore = rule.rules.leader.maxScore;
        }
        // 封顶
        form.value.rules.leader.isTop = rule.rules.leader.topScore > 0;
    }

    // 师门加分
    if ([1, 2].includes(rule.rules.isMasterScore)) {
        // 分数范围
        if (rule.rules.master.minScore === rule.rules.master.maxScore) {
            // 固定的分数
            form.value.isMaster = 2;
            form.value.rules.master.fixedScore = rule.rules.master.minScore;
        } else {
            // 范围分数
            form.value.isMaster = 1;
            form.value.rules.master.minScore = rule.rules.master.minScore;
            form.value.rules.master.maxScore = rule.rules.master.maxScore;
        }
        // 封顶
        form.value.rules.master.isTop = rule.rules.master.topScore > 0;
    }
    isEditing.value = true;
    openModal();
};

// 删除规则
const deleteRule = (id: number) => {
    RuleService.deleteRule(id);
    loadRules();
    ElMessage.success('规则删除成功');
};

// 重置表单
const resetForm = () => {
    form.value = {
    id: new Date().getTime(),
    category: '',
    item: '',
    description: '',
    isLeader: 2,
    isMaster: 0,
    rules: {
        leader: {
            minScore: 0,
            maxScore: 0,
            defaultScore: 0,
            topScore: 50,
            fixedScore: 0,
            isTop: true,
        },
        master: {
            minScore: 0,
            maxScore: 0,
            defaultScore: 0,
            topScore: 50,
            fixedScore: 0,
            isTop: false,
        },
        isMasterScore: 2,
    }
}
};

// 初始化
onMounted(() => {
    RuleService.initialize();
    loadRules();
});
</script>

<style>
.dialog-footer {
    text-align: right;
}

.modal-form .el-form-item {
    margin-bottom: 18px;
}

.modal-form .el-form-item .el-input-number{
    margin-left: 10px;
    margin-right: 10px;
}

.filter-and-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>